package pluto.util;

import java.awt.image.BufferedImage;  
import java.io.ByteArrayInputStream;  
import java.io.ByteArrayOutputStream;  
import java.io.File;  
import java.io.IOException;  
import javax.imageio.ImageIO;  
import sun.misc.BASE64Decoder;  
import sun.misc.BASE64Encoder;  
  
public class ImageToBase64 {  
  static BASE64Encoder encoder = new sun.misc.BASE64Encoder();  
  static BASE64Decoder decoder = new sun.misc.BASE64Decoder(); 
 
    
  public static String getImageBase64(String path){
	  return getImageBase64(path, "png");
  }  
  public static String getImageBase64(String path,String type){
    File f = new File(path);		 
    BufferedImage bi;  
    try {
      bi = ImageIO.read(f);  
      ByteArrayOutputStream baos = new ByteArrayOutputStream();  
      ImageIO.write(bi, type, baos);  
      byte[] bytes = baos.toByteArray();  
      StringBuffer buffer=new StringBuffer();
      buffer.append("data:image/").append(type).append(";base64,").append(encoder.encodeBuffer(bytes).trim());
      return buffer.toString();
      //return "data:image/png;base64,"+encoder.encodeBuffer(bytes).trim();  
    } catch (IOException e) {  
      e.printStackTrace();  
    }  
    return null;  
  }  
    
  // 解码Base64成为图片，保存在D盘根目录下，名字为wjp.png
  public static void base64StringToImage(String base64String){  
    try {  
      byte[] bytes1 = decoder.decodeBuffer(base64String);				
      ByteArrayInputStream bais = new ByteArrayInputStream(bytes1);  
      BufferedImage bi1 =ImageIO.read(bais);  
      File w2 = new File("d://wjp.png");
      ImageIO.write(bi1, "jpg", w2);
    } catch (IOException e) {  
      e.printStackTrace();  
    }  
  }  
  
}
